﻿using Facebook;
using FacebookMvvmLight.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace FacebookMvvmLight.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class FacebookLoginViewModel : ViewModelBase
    {
        private const string AppId = "1436723116549207";
        /// <summary>
        /// Extended permissions is a comma separated list of permissions to ask the user.
        /// </summary>
        /// <remarks>
        /// For extensive list of available extended permissions refer to 
        /// https://developers.facebook.com/docs/reference/api/permissions/
        /// </remarks>
        private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream,user_status";

        private readonly FacebookClient _fb = new FacebookClient();

        private RelayCommand<WebBrowser> _browserLoadedCommand;

        private RelayCommand<NavigationEventArgs> _browserNavigatedCommand;

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public FacebookLoginViewModel(IDataService dataService)
        {
            
        }

        /// <summary>
        /// Gets the Browser Loaded Command.
        /// </summary>
        public RelayCommand<WebBrowser> BrowserLoadedCommand
        {
            get
            {
                return _browserLoadedCommand
                    ?? (_browserLoadedCommand = new RelayCommand<WebBrowser>(
                        (browser) =>
                        {
                            var loginUrl = GetFacebookLoginUrl(AppId, ExtendedPermissions);
                            browser.Navigate(loginUrl);
                        }
                        ));
            }
        }

        private Uri GetFacebookLoginUrl(string appId, string extendedPermissions)
        {
            var parameters = new Dictionary<string, object>();
            parameters["client_id"] = appId;
            parameters["redirect_uri"] = "https://m.facebook.com/connect/login_success.html";
            parameters["response_type"] = "token";
            parameters["display"] = "touch";

            // add the 'scope' only if we have extendedPermissions.
            if (!string.IsNullOrEmpty(extendedPermissions))
            {
                // A comma-delimited list of permissions
                parameters["scope"] = extendedPermissions;
            }
            Uri u = _fb.GetLoginUrl(parameters);
            string url = u.AbsoluteUri.Replace("https://www.facebook.com/dialog", "https://m.facebook.com/dialog");
            return new Uri(url, UriKind.RelativeOrAbsolute);
        }

        /// <summary>
        /// Gets the Browser Navigated Command.
        /// </summary>
        public RelayCommand<NavigationEventArgs> BrowserNavigatedCommand
        {
            get
            {
                return _browserNavigatedCommand
                    ?? (_browserNavigatedCommand = new RelayCommand<NavigationEventArgs>(
                        (e) =>
                        {
                            FacebookOAuthResult oauthResult;
                            if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
                            {
                                return;
                            }

                            if (oauthResult.IsSuccess)
                            {
                                var accessToken = new FacebookAccessToken()
                                {
                                    AccessToken = oauthResult.AccessToken,
                                    Expires = oauthResult.Expires,
                                    IsSuccess = oauthResult.IsSuccess
                                };
                                LoginSucceded(accessToken);
                            }
                            else
                            {
                                // user cancelled
                                Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(oauthResult.ErrorDescription));
                            }
                        }));
            }
        }

        private void LoginSucceded(FacebookAccessToken accessToken)
        {
            var fb = new FacebookClient(accessToken.AccessToken);

            fb.GetCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                    return;
                }
                try
                {
                    var result = (IDictionary<string, object>)e.GetResultData();// status nằm trong đây

                    SendUserProfileToServer(accessToken, ParseProfile(result.ToString()));
                }
                catch (Exception ex)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message));
                }
                //var id = (string)result["id"];
                //Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(result.ToString()));
                //var url = string.Format("/Pages/FacebookInfoPage.xaml?access_token={0}&id={1}", accessToken, id);

                //Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(url, UriKind.Relative)));
            };
            fb.GetAsync("me?fields=id,name,gender,birthday,email,location,picture");//,statuses.fields(message)");
        }

        private FacebookUserProfile ParseProfile(string jsonResult)
        {
            return  JsonConvert.DeserializeObject<FacebookUserProfile>(jsonResult);
        }

        private void SendUserProfileToServer(FacebookAccessToken accessToken, FacebookUserProfile userProfile)
        {
            if (userProfile.error == null)
            {
                // send data to server
            }
            else
            {
                // do something

            }
        }
        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}
    }
}